﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Brainee.Search
{
  /// <summary>
  /// The graph search strategy uses another strategy and filters the states
  /// that have been previously treated. 
  /// </summary>
  /// <remarks>
  /// This strategy can be used to solve problems with many repeated states.
  /// </remarks>
  public class GraphSearchStrategy : ISearchStrategy
  {
    private ISearchStrategy _strategy;
    private HashSet<IState> _knownStates;

    public GraphSearchStrategy (ISearchStrategy strategy)
    {
      _strategy = strategy;
    }

    public void Initialize (IProblem pb)
    {
      // Initialize the known states list
      _knownStates = new HashSet<IState> (pb.StateComparer);

      _strategy.Initialize (pb);
    }

    public bool HasUnexploredStates ()
    {
      return _strategy.HasUnexploredStates ();
    }

    public ISearchState NextState ()
    {
      return _strategy.NextState ();
    }

    public void Expand (ISearchState state, IProblem problem)
    {
      if (!_knownStates.Contains (state.State))
      {
        _knownStates.Add (state.State);
        _strategy.Expand (state, problem);
      }
    }
  }
}
